package exercises.leetcode;

/**
 * <a href="https://leetcode-cn.com/problems/squares-of-a-sorted-array/">
 * 977. 有序数组的平方</a>
 *
 * @author or2
 * @Description 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。
 * @create 2021年09月20日 时间: 17:28
 */
public class No977 {
    public int[] sortedSquares(int[] nums) {
        int[] ans = new int[nums.length];

        int lastIndex = nums.length - 1;
        int leftIndex = 0;

        int size = nums.length - 1;
        while (leftIndex <= lastIndex && nums[leftIndex] < 0) {
            if (nums[lastIndex] > Math.abs(nums[leftIndex])) {
                nums[lastIndex] *= nums[lastIndex];
                ans[size--] = nums[lastIndex--];
            } else {
                nums[leftIndex] *= nums[leftIndex];
                ans[size--] = nums[leftIndex++];
            }
        }

        while (lastIndex >= leftIndex) {
            ans[size--] = nums[lastIndex] * nums[lastIndex--];
        }

        return ans;
    }

    public int[] sortedSquares2(int[] nums) {
        int length = nums.length;
        int[] ans = new int[length];

        int lastIndex = length - 1, leftIndex = 0;

        int size = length - 1;
        while (leftIndex <= lastIndex) {
            if (-nums[leftIndex] > nums[lastIndex])
                ans[size--] = nums[leftIndex] * nums[leftIndex--];
            else
                ans[size--] = nums[lastIndex] * nums[lastIndex--];
        }

        return ans;
    }
}
